/**
 * lilyweb's password utilities
 * @module lib/lilywebPassword
 */

//const { clear } = require("console");
const crypto = require("crypto");

/**
 * Return a salted and hashed password entry from a clear text password.
 * @param {string} clearTextPassword
 * @return {object} passwordEntry an object with two string properties:
 *      salt - The salt used for the password.
 *      hash - The sha1 hash of the password and salt
 */
function makePasswordEntry(clearTextPassword) {
  let cipher = crypto.createHash("sha1");
  let salt = crypto.randomBytes(8).toString("hex");
  cipher.update(clearTextPassword + salt);
  return { salt: salt, hash: cipher.digest("hex") };
}

/**
 * Return true if the specified clear text password and salt generates the specified hash.
 * @param {string} hash
 * @param {string} salt
 * @param {string} clearTextPassword
 * @return {boolean} whether the password matches hash and salt
 */
function doesPasswordMatch(hash, salt, clearTextPassword) {
  let cipher = crypto.createHash("sha1");
  cipher.update(clearTextPassword + salt);
  return cipher.digest("hex") === hash;
}

/**
 * Validate user password
 * At least one lower case letter [a-z]
 * At least one upper case letter [A-Z]
 * At least one number [0-9]
 * At least one special character not in [a-zA-Z0-9_]
 * At least 8 digits long
 * @param {string} password - password
 * @returns
 */
function validatePassword(password) {
  if (
    /[a-z]/.test(password) &&
    /[A-Z]/.test(password) &&
    /\d/.test(password) &&
    /\W/.test(password) &&
    password.length >= 8
  ) {
    return true;
  }
  return false;
}

module.exports = {
  makePasswordEntry,
  doesPasswordMatch,
  validatePassword,
};
